package com.wanwanbookstore.dao;

import com.wanwanbookstore.entity.CartItem;
import com.wanwanbookstore.entity.Book;
import com.wanwanbookstore.utils.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CartDAO {
    // 获取用户的购物车
    public List<CartItem> getCartByUserId(int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<CartItem> cartItems = new ArrayList<>();
        BookDAO bookDAO = new BookDAO();
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM cart_item WHERE user_id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();
            while (rs.next()) {
                CartItem item = new CartItem();
                item.setId(rs.getInt("id"));
                item.setUserId(rs.getInt("user_id"));
                item.setBookId(rs.getInt("book_id"));
                item.setQuantity(rs.getInt("quantity"));
                // 查询图书信息
                Book book = bookDAO.getBookById(item.getBookId());
                item.setBook(book);
                cartItems.add(item);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cartItems;
    }

    // 添加商品到购物车
    public boolean addToCart(int userId, int bookId, int quantity) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            // 先检查是否已存在
            String checkSql = "SELECT * FROM cart_item WHERE user_id = ? AND book_id = ?";
            stmt = conn.prepareStatement(checkSql);
            stmt.setInt(1, userId);
            stmt.setInt(2, bookId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                // 已存在，更新数量
                int id = rs.getInt("id");
                int currentQuantity = rs.getInt("quantity");
                rs.close();
                stmt.close();
                String updateSql = "UPDATE cart_item SET quantity = ? WHERE id = ?";
                stmt = conn.prepareStatement(updateSql);
                stmt.setInt(1, currentQuantity + quantity);
                stmt.setInt(2, id);
                return stmt.executeUpdate() > 0;
            } else {
                // 不存在，新增
                rs.close();
                stmt.close();
                String insertSql = "INSERT INTO cart_item (user_id, book_id, quantity) VALUES (?, ?, ?)";
                stmt = conn.prepareStatement(insertSql);
                stmt.setInt(1, userId);
                stmt.setInt(2, bookId);
                stmt.setInt(3, quantity);
                return stmt.executeUpdate() > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    // 更新购物车商品数量
    public boolean updateCartItem(int id, int quantity) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE cart_item SET quantity = ? WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, quantity);
            stmt.setInt(2, id);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    // 删除购物车商品
    public boolean deleteCartItem(int id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM cart_item WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    // 清空用户购物车
    public boolean clearCart(int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM cart_item WHERE user_id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    // 检查购物车中是否有已下架的商品
    public List<CartItem> checkDeletedBooks(int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<CartItem> deletedItems = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT c.*, b.is_deleted FROM cart_item c JOIN book b ON c.book_id = b.id WHERE c.user_id = ? AND b.is_deleted = 1";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();
            BookDAO bookDAO = new BookDAO();
            while (rs.next()) {
                CartItem item = new CartItem();
                item.setId(rs.getInt("id"));
                item.setUserId(rs.getInt("user_id"));
                item.setBookId(rs.getInt("book_id"));
                item.setQuantity(rs.getInt("quantity"));
                Book book = bookDAO.getBookById(item.getBookId());
                item.setBook(book);
                deletedItems.add(item);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
            try {
                if (stmt != null) stmt.close();
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return deletedItems;
    }
}